<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-title">管理员登录</div>
      <el-form status-icon :model="loginForm" :rules="rules" ref="ruleForm" class="login-form">
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              :prefix-icon="User"
              placeholder="用户名"
              @keyup.enter.native="login" />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              :prefix-icon="Lock"
              show-password
              placeholder="密码"
              @keyup.enter.native="login" />
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="login">登录</el-button>
    </div>
  </div>
</template>

<script setup>
import { User ,Lock} from '@element-plus/icons-vue'
import {ref,getCurrentInstance} from "vue";
import {useUserStore} from "../store/useUserStore";
import {useRouter} from "vue-router";
import request from "../utils/request";
import {tokenName,userName} from "../config";


const {proxy} = getCurrentInstance()
const userStore = useUserStore()
const router = useRouter()
const loginForm = ref({
  username: 'admin',
  password: 'admin'
})
const rules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
}


// 登录
const login = () => {
  proxy.$refs.ruleForm.validate(valid => {
    if (valid) {
      request.post('/auth/login', loginForm.value).then(res => {
        if (res.code === 1){
          userStore.user = res.data
          localStorage.setItem(tokenName,res.data.token.tokenValue)
          localStorage.setItem(userName,JSON.stringify(res.data))
          proxy.$message.success('登录成功')
          router.push('/home')
        }else {
          proxy.$message.error(res.message)
        }
      })
    } else {
      return false
    }
  })
}
</script>

<style scoped>
.login-container {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background-color: #2d3a4b;
}
.login-card {
  background: #fff;
  padding: 80px 60px 80px;
  width: 350px;
  margin: 10% auto;
}
.login-title {
  color: #303133;
  font-weight: bold;
  font-size: 1rem;
}
.login-form {
  margin-top: 1.2rem;
}
.login-card button {
  margin-top: 1rem;
  width: 100%;
}
</style>
